package com.iyao_app.mvp.laterly;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.iyao_app.Friends.ChatActivity;
import com.iyao_app.R;
import com.iyao_app.adapter.LatelyPersonsBotoomAdapter;
import com.iyao_app.adapter.LatelyPersonsCenterAdapter;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.HomeData;
import com.iyao_app.entry.Manor;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.SceneUser;
import com.iyao_app.entry.User;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.manager.GalleryLayoutManager;
import com.iyao_app.manager.GalleryLayoutManager_;
import com.iyao_app.mvp.other.OtherHomeActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.ToastUtil;
import com.iyao_app.view.LetterSpacingTextView;
import com.iyao_app.view.ScaleTransformer;
import com.iyao_app.view.ScaleTransformer_;
import com.iyaowoqu.base_library.util.LogUtil;
import com.iyaowoqu.base_library.util.PopupWindowUtils;
import com.iyaowoqu.base_library.util.Utils;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/21.
 */

public class LatelyPersonsActivity extends BaseActivityWithHead {
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.iv_next)
    ImageView mIvNext;
    @BindView(R.id.tv_tab_1)
    LetterSpacingTextView mTvTab1;
    @BindView(R.id.v_tab_1)
    View mVTab1;
    @BindView(R.id.tab_1)
    LinearLayout mTab1;
    @BindView(R.id.tv_tab_2)
    LetterSpacingTextView mTvTab2;
    @BindView(R.id.v_tab_2)
    View mVTab2;
    @BindView(R.id.tab_2)
    LinearLayout mTab2;
    @BindView(R.id.tv_tab_3)
    LetterSpacingTextView mTvTab3;
    @BindView(R.id.v_tab_3)
    View mVTab3;
    @BindView(R.id.tab_3)
    LinearLayout mTab3;
    @BindView(R.id.rv_center)
    RecyclerView mRvCenter;
    @BindView(R.id.rv_bottom)
    RecyclerView mRvBottom;
    @BindView(R.id.lin_root)
    LinearLayout mLinRoot;

    final int ALL = 0;
    final int ONLY_MAN = 1;
    final int ONLY_WOMAN = 2;
    int mode = ALL;
    private int type;
    private Manor manor;
    private LatelyPersonsCenterAdapter adapter;
    private LatelyPersonsBotoomAdapter pictureAdapter;
    List<SceneUser> users = new ArrayList<>();

    private GalleryLayoutManager layoutManager1;

    private GalleryLayoutManager_ linearLayoutManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lately_person);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra(Contants.TYPE, 0);
        manor = (Manor) getIntent().getSerializableExtra(Contants.OTHER_FIELD);
//        manor.sceneId = "55bc8be085ca422a89717a7d9ae9d95a";
        initData();

    }

    private int selectType = 0;

    MyHandler myHandler = new MyHandler(this);

    static class MyHandler extends Handler {
        WeakReference<LatelyPersonsActivity> mActivityReference;

        MyHandler(LatelyPersonsActivity activity) {
            mActivityReference = new WeakReference<LatelyPersonsActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final LatelyPersonsActivity activity = mActivityReference.get();
            int position = (int) msg.obj;
            switch (msg.what) {
                case 0:
                    if (activity != null) {
                        LogUtil.e("====handleMessage======" + position);
                        for (int i = 0; i < activity.pictureAdapter.getData().size(); i++) {
                            SceneUser user = activity.pictureAdapter.getData().get(i);
                            if (i == position) {
                                user.isSelect = 1;
                            } else {
                                user.isSelect = 0;
                            }
                        }
                        activity.pictureAdapter.notifyDataSetChanged();
                    }
                    break;
            }


        }
    }

    private boolean center = false;
    private boolean botoom = false;
    int p = 0;

    private void initData() {
        switch (type) {
            case 0:
                setTitleTV("签到的人");
                break;
            case 1:
                setTitleTV("来过这里的好友");
                break;
            case 2:
                setTitleTV("常来附近的人");
                break;
        }
        getData(type);
        changeMode(mode);

        layoutManager1 = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);
        layoutManager1.attach(mRvCenter, 0);
        layoutManager1.setItemTransformer(new ScaleTransformer());
        layoutManager1.setOnItemSelectedListener(new GalleryLayoutManager.OnItemSelectedListener() {
            @Override
            public void onItemSelected(RecyclerView recyclerView, View item, final int position) {

                if (center && !botoom) {
                    int curSelectedPosition = linearLayoutManager.getCurSelectedPosition();
                    if (curSelectedPosition != position + 2) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvBottom.smoothScrollToPosition(position + 2);

                            }
                        });

                        Message message = myHandler.obtainMessage();
                        message.what = 0;
                        message.obj = position + 2;
                        myHandler.sendMessage(message);
                        center = false;
                    }

                }
            }
        });
        mRvCenter.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                center = true;
                return false;
            }
        });
        mRvBottom.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                botoom = true;
                return false;
            }
        });
        adapter = new LatelyPersonsCenterAdapter(null);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                SceneUser item = (SceneUser) adapter.getItem(position);
                if (view.getId() == R.id.tv_guanzhu) {
                    switch (item.friendShip) {
                        case -1:
                            guanzhu(item.userId,position);

                            break;
                        case 1:
                            cancleFriend(item.userId,position);
                            break;
                        case 2:
                            guanzhu(item.userId,position);
                            break;
                        case 4:
                            Intent intent = new Intent(LatelyPersonsActivity.this, ChatActivity.class);
                            intent.putExtra("username", item.userId);
                            intent.putExtra("nickname", item.nickName);
                            intent.putExtra("favicon", item.avatarUrl);
                            break;
                        case 5:
                            guanzhu(item.userId,position);
                            break;
                    }
                }

            }
        });
        mRvCenter.setAdapter(adapter);
        adapter.setOnItemClickListener(
                new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        SceneUser item = (SceneUser) adapter.getItem(position);
                        Intent intent = new Intent(LatelyPersonsActivity.this, OtherHomeActivity.class);
                        intent.putExtra(Contants.TYPE, String.valueOf(item.userId));
                        startActivity(intent);
                    }
                }
        );
        linearLayoutManager = new GalleryLayoutManager_(GalleryLayoutManager_.HORIZONTAL);
        linearLayoutManager.attach(mRvBottom, 0);
        linearLayoutManager.setItemTransformer(new ScaleTransformer_());

        linearLayoutManager.setOnItemSelectedListener(new GalleryLayoutManager_.OnItemSelectedListener() {
            @Override
            public void onItemSelected(RecyclerView recyclerView, View item, final int position) {
                if (botoom && !center) {
                    int curSelectedPosition = layoutManager1.getCurSelectedPosition();
                    if (position < 2) {
                        Message message = myHandler.obtainMessage();
                        message.what = 0;
                        message.obj = 2;
                        myHandler.sendMessage(message);
                        if (curSelectedPosition != 0) {
                            p = 0;

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRvCenter.smoothScrollToPosition(p);
                                }
                            });
                        }
                    } else if (position > pictureAdapter.getData().size() - 3) {
                        Message message = myHandler.obtainMessage();
                        message.what = 0;
                        message.obj = pictureAdapter.getData().size() - 3;
                        myHandler.sendMessage(message);
                        if (curSelectedPosition != adapter.getData().size() - 1) {
                            p = adapter.getData().size() - 1;

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRvCenter.smoothScrollToPosition(p);
                                }
                            });
                        }
                    } else {
                        Message message = myHandler.obtainMessage();
                        message.what = 0;
                        message.obj = position;
                        myHandler.sendMessage(message);
                        if (curSelectedPosition != position - 2) {
                            p = position - 2;

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRvCenter.smoothScrollToPosition(p);
                                }
                            });
                        }
                    }
                    botoom = false;

                }
            }
        });

        pictureAdapter = new LatelyPersonsBotoomAdapter(null);
        mRvBottom.setHasFixedSize(true);
        mRvBottom.setAdapter(pictureAdapter);

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final BaseQuickAdapter adapter, View view, final int position) {
                int curSelectedPosition = layoutManager1.getCurSelectedPosition();
                if (position < 2) {
                    Message message = myHandler.obtainMessage();
                    message.what = 0;
                    message.obj = 0;
                    myHandler.sendMessage(message);
                    if (curSelectedPosition != 0) {
                        p = 0;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvCenter.smoothScrollToPosition(p);
                            }
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvBottom.smoothScrollToPosition(0);
                            }
                        });
                    }
                } else if (position > pictureAdapter.getData().size() - 3) {
                    Message message = myHandler.obtainMessage();
                    message.what = 0;
                    message.obj = adapter.getData().size() - 1;
                    myHandler.sendMessage(message);
                    if (curSelectedPosition != adapter.getData().size() - 1) {
                        p = adapter.getData().size() - 1;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvCenter.smoothScrollToPosition(p);
                            }
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvBottom.smoothScrollToPosition(adapter.getData().size() - 1);
                            }
                        });
                    }
                } else {
                    Message message = myHandler.obtainMessage();
                    message.what = 0;
                    message.obj = position;
                    myHandler.sendMessage(message);
                    if (curSelectedPosition != position - 2) {
                        p = position - 2;

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvCenter.smoothScrollToPosition(p);
                            }
                        });
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mRvBottom.smoothScrollToPosition(position);
                            }
                        });
                    }
                }
                botoom = false;
            }
        });
    }

    @OnClick({R.id.tab_1, R.id.tab_2, R.id.tab_3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tab_1:
                mode = ONLY_MAN;
                changeMode(mode);
                getData(type);
                break;
            case R.id.tab_2:
                mode = ONLY_WOMAN;
                changeMode(mode);
                getData(type);
//                layoutManager1.smoothScrollToPosition();
                break;
            case R.id.tab_3:

                mode = ALL;
                changeMode(mode);
                getData(type);
                break;
        }
    }

    private void changeMode(int mode) {
        switch (mode) {
            case ALL:
                mVTab1.setVisibility(View.INVISIBLE);
                mTvTab1.setTextColor(ResourcesUtils.getColor(R.color.white));
                mVTab2.setVisibility(View.INVISIBLE);
                mTvTab2.setTextColor(ResourcesUtils.getColor(R.color.white));
                mVTab3.setVisibility(View.VISIBLE);
                mTvTab3.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                break;
            case ONLY_MAN:
                mVTab1.setVisibility(View.VISIBLE);
                mTvTab1.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                mVTab2.setVisibility(View.INVISIBLE);
                mTvTab2.setTextColor(ResourcesUtils.getColor(R.color.white));
                mVTab3.setVisibility(View.INVISIBLE);
                mTvTab3.setTextColor(ResourcesUtils.getColor(R.color.white));
                break;
            case ONLY_WOMAN:
                mVTab1.setVisibility(View.INVISIBLE);
                mTvTab1.setTextColor(ResourcesUtils.getColor(R.color.white));
                mVTab2.setVisibility(View.VISIBLE);
                mTvTab2.setTextColor(ResourcesUtils.getColor(R.color.app_orange_ff773d));
                mVTab3.setVisibility(View.INVISIBLE);
                mTvTab3.setTextColor(ResourcesUtils.getColor(R.color.white));
                break;
        }
    }

    private void getData(int type) {
        final User user = DbUtil.getUser();
        switch (type) {
            case 0://签到的人
                /**
                 * 当前场景签到用户
                 */
                NetUtils.getInstance().currentSceneUser(manor.sceneId, 1, 40, mode, new NetCallBack() {
                    @Override
                    public void onSuccess(String message, int code, String response, ResultModel model) {
                        if (code == Contants.SUCCESS_CODE) {
                            if (model == null) return;
                            HomeData homeData = model.getModel();
                            if (homeData != null) {
                                List<SceneUser> users = homeData.getUsers();
                                if (users == null || users.size() == 0) {
                                    adapter.getData().clear();
                                    adapter.notifyDataSetChanged();
                                    pictureAdapter.getData().clear();
                                    pictureAdapter.notifyDataSetChanged();
                                } else {
                                    setData(users);
                                }

                            }
                        }
                    }

                    @Override
                    public void onFail(String message, int code) {

                    }
                }, HomeData.class);
                break;
            case 1://来过这里的好友
                NetUtils.getInstance().currentSceneFriend(user.id, manor.sceneId, 1, 40, mode, new NetCallBack() {
                    @Override
                    public void onSuccess(String message, int code, String response, ResultModel model) {
                        if (code == Contants.SUCCESS_CODE) {
                            if (model == null) return;
                            HomeData homeData = model.getModel();
                            if (homeData != null) {
                                List<SceneUser> users = homeData.getUsers();
                                if (users == null || users.size() == 0) {
                                    adapter.getData().clear();
                                    adapter.notifyDataSetChanged();
                                    pictureAdapter.getData().clear();
                                    pictureAdapter.notifyDataSetChanged();
                                } else {
                                    setData(users);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFail(String message, int code) {

                    }
                }, HomeData.class);
                break;
            case 2://常来附近的人
                /**
                 * 获取在当前场景附近签到的用户
                 */
                NetUtils.getInstance().currentSceneRoundUser(user.id, manor.sceneId, 1, 40, mode, new NetCallBack() {
                    @Override
                    public void onSuccess(String message, int code, String response, ResultModel model) {
                        if (code == Contants.SUCCESS_CODE) {
                            if (model == null) return;
                            HomeData homeData = model.getModel();
                            if (homeData != null) {
                                List<SceneUser> users = homeData.getUsers();
                                if (users == null || users.size() == 0) {
                                    adapter.getData().clear();
                                    adapter.notifyDataSetChanged();
                                    pictureAdapter.getData().clear();
                                    pictureAdapter.notifyDataSetChanged();
                                } else {
                                    setData(users);
                                }
                            }
                        }
                    }

                    @Override
                    public void onFail(String message, int code) {

                    }
                }, HomeData.class);
                break;
        }

    }


    public void setData(List<SceneUser> data) {
        adapter.getData().clear();
        adapter.notifyDataSetChanged();
        users.clear();
        pictureAdapter.getData().clear();
        pictureAdapter.notifyDataSetChanged();
        if (data != null && data.size() > 0) {
            adapter.addData(data);
            users.add(new SceneUser());
            users.add(new SceneUser());
            pictureAdapter.addData(users);
            SceneUser sceneUser = data.get(0);
            sceneUser.isSelect = 1;
            pictureAdapter.addData(data);
            pictureAdapter.addData(users);
            mRvBottom.smoothScrollToPosition(2);
        }
    }

    private void cancleFriend(final String userId, final int position) {

        final PopupWindowUtils popupWindowUtils = PopupWindowUtils.getInstance();
        popupWindowUtils.attachActivity(LatelyPersonsActivity.this, R.layout.item_popupwindow, mLinRoot)
                .wiewSize(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
                .location(Gravity.BOTTOM, 0, Utils.getBottomStatusHeight(this))
                .focuseAble(true)
                .Animation(PopupWindowUtils.ANIMATION_BOTTOM)
                .setPopupWindowItemViewClickListener(new PopupWindowUtils.SetonPopWindowItemViewClickListenter() {
                    @Override
                    public void onPopWindowItemViewClickListener(int id) {
                        switch (id) {
                            case R.id.pop_financial://确认
                                unfollowFriend(userId, position);
                                popupWindowUtils.dissMissPopWindow();
                                break;
                            case R.id.pop_manage://取消
                                popupWindowUtils.dissMissPopWindow();
                                break;
                        }
                    }
                }, R.id.pop_financial, R.id.pop_manage)
                .show();
    }

    private void guanzhu(String id, final int position) {

        NetUtils.getInstance().followFriend(id, null, null, 0, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {
                ToastUtil.showToast(LatelyPersonsActivity.this, "关注成功");
                SceneUser sceneUser = adapter.getData().get(position);
                if (sceneUser.friendShip==5){
                    sceneUser.friendShip = 4;
                }else {
                    sceneUser.friendShip = 1;
                }

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }

    private void unfollowFriend(String id, final int position) {

        NetUtils.getInstance().unfollowFriend(id, new NetCallBack() {
            @Override
            public void onSuccess(String message, final int code, String response, final ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    ToastUtil.showToast(LatelyPersonsActivity.this, "取消关注成功");
                    SceneUser sceneUser = adapter.getData().get(position);
                    sceneUser.friendShip = -1;

                    adapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, null);
    }
}
